import { Injectable } from '@angular/core';
import { Action, State, StateContext } from '@ngxs/store';
import { PageAction } from '.';

export const DEFAULT_PAGE: PageStateModel = {
  pageNo: 1,
  pageSize: 18,
  orderBy: 'id',
  order: 'desc',
  count: 0,
  param: {},
};

export interface PageStateModel {
  pageNo: number;
  pageSize: number;
  orderBy: string;
  order: string;
  count: number;
  param: any;
}

@State<PageStateModel>({
  name: 'page',
  defaults: {
    ...DEFAULT_PAGE,
  },
})
@Injectable({
  providedIn: 'root',
})
export class PageState {

  @Action(PageAction.Reset)
  Reset(ctx: StateContext<PageStateModel>) {
    let state = ctx.getState();
    let result = {...DEFAULT_PAGE};
    if (state) {
      result.pageSize = state.pageSize;
    }
    ctx.patchState(result);
  }

  @Action(PageAction.ChangeCount)
  ChangeCount(ctx: StateContext<PageStateModel>, {count}: PageAction.ChangeCount) {
    ctx.patchState({count});
  }

  @Action(PageAction.ChangeNo)
  ChangeNo(ctx: StateContext<PageStateModel>, {pageNo}: PageAction.ChangeNo) {
    ctx.patchState({pageNo});
  }

  @Action(PageAction.ChangeSize)
  ChangeSize(ctx: StateContext<PageStateModel>, {pageSize}: PageAction.ChangeSize) {
    ctx.patchState({pageSize});
  }
}
